package vinux.web.common.es;

import java.sql.SQLFeatureNotSupportedException;

import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.nlpcn.es4sql.SearchDao;
import org.nlpcn.es4sql.exception.SqlParseException;
import org.nlpcn.es4sql.query.SqlElasticUpdateRequestBuilder;

import vinux.service.common.config.JDBCConfig;
import vinux.service.core.utils.LoggerUtils;
/**
 * ES通用查询工具
 * @author tongchuanwei
 *
 */
public class SearchUtil {

	private static Client client=getClient();
	private static SearchDao searchDao=getSearchDao();
   
	
	public static SearchDao getSearchDao() {
		searchDao = new SearchDao(client);
		return searchDao;
	}

	@SuppressWarnings("resource")
	public static Client getClient() {
		/**
		 * "client.transport.sniff",true : 自动查找当前同一网段的相同节点为集群
		 */
		String ip = JDBCConfig.getProperty("es.ip");
		String port = JDBCConfig.getProperty("es.tcp.port");
		String clusterName = JDBCConfig.getProperty("es.cluster.name");
		String message = "当前ES获取的参数:ip[%s],port[%s],es.cluster.name[%s]";
		LoggerUtils.debug(SearchUtil.class, String.format(message, ip,port,clusterName));
		Client client = new TransportClient(ImmutableSettings.settingsBuilder()
				.put("client.transport.sniff",true)
					.put("cluster.name", clusterName)
						.build())
							.addTransportAddress(new InetSocketTransportAddress(ip,Integer.parseInt(port)));
		return client;
	}
	
	
	/**
	 * SQL统一解析ES语法并执行查询
	 * 
	 * @param query
	 * @return
	 * @throws SqlParseException
	 * @throws SQLFeatureNotSupportedException
	 * @throws SQLFeatureNotSupportedException
	 */
	public static SearchRequestBuilder query(String query) throws SqlParseException, SQLFeatureNotSupportedException, SQLFeatureNotSupportedException {
		SearchRequestBuilder select = (SearchRequestBuilder)searchDao.explain(query).explain().getBuilder();
		return select;
	}
	
	/**
	 * SQL统一解析ES语法并执行更新
	 * @param sql
	 * @return
	 */
	public static  SqlElasticUpdateRequestBuilder update(String sql) {
		SqlElasticUpdateRequestBuilder select = null;
		try {
			select = (SqlElasticUpdateRequestBuilder)searchDao.explain(sql).explain();
		} catch (Exception e) {
			System.out.println("没有符合条件的更新数据，无法执行操作!");
		}
		return select;
	}
	
	/**
	 * SQL统一解析ES语法并执行删除
	 * @param deleteStatement
	 * @throws SqlParseException
	 * @throws SQLFeatureNotSupportedException
	 */
	public static void delete(String deleteStatement) throws SqlParseException, SQLFeatureNotSupportedException {
		searchDao.explain(deleteStatement).explain().get();
	}
	
	public static void main(String[] args) {
		SearchUtil.getSearchDao();
	}
}
